<?php
/**
 * This is a controller config page.
 *
 * This controller would be responsible for applying actions in classical admin area.
 * it could be any changes concerned mass applying
 *
 * @author Pavel Savchuk
 */

class Backend_ConfigController extends RCMS_Core_BaseController {

	public function init() {
		parent::init();
		$this->checkLogin();
		$this->_model = new Default_Model_ConfigModel();
		$this->_cache->clean('all');
	}

	public function initDataForConfigForm($isAdmin) {

		$configForm =  new RCMS_Form_ConfigForm();
		$configArray = $this->_model->selectAll();
		$userData = $this->_model->selectSuperAdmin();
		$superAdmin = new RCMS_Object_User_User($userData['userId']);


		$configForm->getElement('currentTheme')->setValue($configArray['current_theme']);

		$configForm->getElement('defaultPage')->setValue($configArray['default_page']);
		$configForm->getElement('zfp')->setValue($configArray['zfp']);

		$configForm->getElement('adminEmail')->setValue($configArray['admin_email']);

		$configForm->getElement('imgSmall')->setValue($configArray['img_small']);
		$configForm->getElement('imgMedium')->setValue($configArray['img_medium']);
		$configForm->getElement('imgLarge')->setValue($configArray['img_large']);

		$configForm->getElement('imgPageDescriptionSmall')->setValue($configArray['img_page_desc_small']);
		$configForm->getElement('imgPageDescriptionLarge')->setValue($configArray['img_page_desc_large']);

		$configForm->getElement('smtpHost')->setValue($configArray['smtp_host']);
		$configForm->getElement('smtpPassword')->setValue($configArray['smtp_password']);
		$configForm->getElement('smtpLogin')->setValue($configArray['smtp_login']);
		$configForm->getElement('useSmtp')->setValue($configArray['use_smtp']);
		$configForm->getElement('pageImageTeaser')->setValue($configArray['page_teaser_size']);
		$configForm->getElement('languages')->addMultiOptions($this->_makeLangsOptions($configArray['translate_language']));
		$configForm->getElement('languages')->setValue($configArray['translate_language']);
		$configForm->getElement('pluginCache')->setValue($configArray['plugin_cache']);

		if($isAdmin) {
			$configForm->getElement('loginUser')->setValue($superAdmin->getLogin());
		// $configForm->getElement('passwordUser')->setValue("1111");
		}else {
			$configForm->removeElement('loginUser');
			$configForm->removeElement('passwordUser');
		}

		$configForm->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/config.phtml'))
		));
		return $configForm;
	}

	/**
	 * This method is an action which is responsible for adding new page
	 * @return void
	 */
	public function manageconfigAction() {
		$this->view->superAdmin=false;
		//configurate settings variables from config file
		$websitePath  = unserialize(Zend_Registry::get('config'))->website->website->path;
		$this->_helper->getHelper('layout')->disableLayout();

		$userObj = unserialize($this->_session->currentUser);
		$result = $this->_model->selectUserRole($userObj->getId());

		if($result) {
			$this->view->superAdmin = true;
		}

		$configForm = $this->initDataForConfigForm($this->view->superAdmin);


		//assing form to template
		$this->view->form  =  $configForm;
		//if request is POST and everything is valid
		if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {
				$flagError=false;
				$data = $this->view->form->getValues();
				//var_dump($data); die();
				$configData = array(
					'admin_email'         => $data['adminEmail'],
					'img_small'           => $data['imgSmall'],
					'img_medium'          => $data['imgMedium'],
					'img_large'           => $data['imgLarge'],
//					'img_page_desc_large' => $data['imgPageDescriptionLarge'],
//					'img_page_desc_small' => $data['imgPageDescriptionSmall'],
					'smtp_host'           => $data['smtpHost'],
					'smtp_password'       => $data['smtpPassword'],
					'smtp_login'          => $data['smtpLogin'],
					'use_smtp'            => $data['useSmtp'],
					'page_teaser_size'    => $data['pageImageTeaser'],
					'translate_language'  => $data['languages']
					//'plugin_cache'        => $data['pluginCache']
				);

				$userData = $this->_model->selectSuperAdmin();
				$superAdmin = new RCMS_Object_User_User($userData['userId']);
				if($this->view->superAdmin) {
					$login = $data['loginUser'];
					$password = $data['passwordUser'];
					if($password!="******" && $superAdmin->getPassword()!=md5($password)) {
						$superAdmin->setPassword(md5($password));
					}

					if($login!="" && $login!=$superAdmin->getLogin()) {
						if(!$this->_model->selectUserLogin($login)) {
							$superAdmin->setLogin($login);
						}else {
							$flagError=true;
							$this->view->loginError = "Entered login name is already exists.";
						}
					}
					$superAdmin->save();
				}
				$configTableData = $this->_model->selectAll();
				if(!$flagError) {
					foreach ($configData as $key => $value) {
						if($key != 'smtp_password') {
							$res = $this->_model->updateConfigVariableByName($key, $value);
						}
						else {
							if($value != '******' && $configTableData['smtp_password'] != $value) {
								$this->_model->updateConfigVariableByName('smtp_password', $value);
							}
						}
					}
					$this->view->hide = true;
				}
			} else {
				$this->view->errorElements = $this->processErrors($this->view->form->getMessages());
			}
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This method processing errors for config form
	 *
	 * @param  array $array
	 * @return void
	 */
	public function processErrors($array) {
		$messages = array();
		$htmlUl = "";

		foreach ($array as $key => $value) {
			switch ($key) {
				case 'adminEmail':
					if(isset($value['isEmpty']))
						$messages[]="Admin Email field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Admin Email field can only contain letters,digits, '@', '.' and '-' .";
					break;

				case 'imgSmall':
					if(isset($value['isEmpty']))
						$messages[]="Small Image field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Small Image field can contain digits only.";
					break;

				case 'imgMedium':
					if(isset($value['isEmpty']))
						$messages[]="Medium Image field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Medium Image size field can contain digits only.";
					break;

				case 'imgLarge':
					if(isset($value['isEmpty']))
						$messages[]="Large Image field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Large Image field can contain only digits.";
					break;

				case 'pageImageTeaser':
					if(isset($value['isEmpty']))
						$messages[]="Page Teaser Image field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Page Teaser Image field can contain digits only.";
					break;

				case 'smtpHost':
					if(isset($value['regexNotMatch']))
						$messages[]="Smtp Host field can only contain letters,digits, '.' and '-' .";
					break;

				case 'smtpLogin':
					if(isset($value['regexNotMatch']))
						$messages[]="Smtp Login field can only contain letters,digits, '.' and '-' .";
					break;


				case 'imgMaxWidth':
					if(isset($value['isEmpty']))
						$messages[]="Image Max Width field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Image Max Width field can contain digits only.";
					break;

				case 'videoWidth':
					if(isset($value['isEmpty']))
						$messages[]="Video Width field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Video Width field can contain digits only.";
					break;

				case 'videoHeight':
					if(isset($value['isEmpty']))
						$messages[]="Video Height field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Video Height field can contain digits only.";
					break;

				case 'loginUser':
					if(isset($value['isEmpty']))
						$messages[]="Login field can't be empty.";
					break;

				case 'passwordUser':
					if(isset($value['isEmpty']))
						$messages[]="Password field can't be empty.";
					if(isset($value['stringLengthTooShort']))
						$messages[]="Password field can't contain less than 5 characters.";
					if(isset($value['stringLengthTooLong']))
						$messages[]="Password field can't contain more than 255 characters.";
					if(isset($value['regexNotMatch']))
						$messages[]="REGEX";
					break;
			}
		}

		if(!empty($messages)) {
			$htmlUl = "<ul>";
			foreach ($messages as $message) {
				$htmlUl .= "<li>".$message."</li>";
			}
			$htmlUl .= "<ul>";
			return $htmlUl;
		}
		return null;
	}

	private function _makeLangsOptions($currSysLng) {
		$langList = array();
		$avialLanguages = RCMS_Tools_FilesystemTools::findFilesByExt('downloads', 'lng');
		if(!$avialLanguages || empty($avialLanguages)) {
			return array($currSysLng => $currSysLng);
		}
		foreach ($avialLanguages as $lang) {
			$lang = str_replace('.lng', '', $lang);
			$langList[$lang] = $lang;
		}
		//var_dump($langList);die();
		return $langList;
	}
}


